//
//  AQCollectionViewLayout.m
//  项目二
//
//  Created by rimi on 16/5/25.
//  Copyright © 2016年 objective. All rights reserved.
//

#import "AQCollectionViewLayout.h"
@interface AQCollectionViewLayout()
/**itemWidth*/
@property (nonatomic ,assign) CGFloat itemWidth;
/**记录每列高度字典*/
@property (nonatomic ,strong) NSMutableDictionary *dict;
/**存储item属性数组*/
@property (nonatomic ,strong) NSMutableArray *attributeArray;
/**计算item高度的回调block*/
@property (nonatomic ,copy) CGFloat(^myBlock)(NSIndexPath *indexPath ,CGFloat itemWidth);
@end

@implementation AQCollectionViewLayout
-(instancetype)init{
    self = [super init];
    if (self) {
        self.column = 3;
        self.columSpacing = 10.0f;
        self.rowSpacing = 10.0f;
        self.sectionEdg = UIEdgeInsetsMake(20, 10, 10, 10);
        self.attributeArray = [NSMutableArray array];
        self.dict = [NSMutableDictionary dictionary];
    }
    return self;
}
/**block的回调*/
-(void)compeleteItemHeightWithBlock:(CGFloat (^)(NSIndexPath *, CGFloat))block{
    self.myBlock = block;
}

/**准备好布局的时候调用*/
- (void)prepareLayout{
    NSLog(@"%s",__func__);
    //记录每一列的当前高度
    for (int i = 0; i < self.column; ++i) {
        NSString *key = [NSString stringWithFormat:@"%d",i];
        self.dict[key] = [NSNumber numberWithFloat:self.sectionEdg.top];
    }
    //计算itemWidth
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    self.itemWidth = (width - self.sectionEdg.left - self.sectionEdg.right - (self.column - 1) * self.columSpacing) / self.column;
    
    //获取collectionView的item个数
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    for (int i = 0; i < count; ++i) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        //获取到每个对应indexPath下item的属性
        UICollectionViewLayoutAttributes *attribute = [self layoutAttributesForItemAtIndexPath:indexPath];
        
        [self.attributeArray addObject:attribute];
    }

}
/**
 *  返回当前显示视图中的item属性数组
 *
 *  @param rect 当前显示窗口的frame
 *
 *  @return array可以包含所有的item属性，它可以自动进行判断加载
     返回在collectionView的可见范围内(bounds)所有item对应的layoutAttrure对象装成的数组
 */
- (NSArray <UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    NSLog(@"%s",__func__);
    return self.attributeArray;
}

/**
 *  具体配置每个item的属性方法
 *
 *  @param indexPath item的具体位置
 *
 *  @return 对应位置下的item属性
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    //在item当中需要通过indexPath进行属性创建
    UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //在其中配置item的具体属性（瀑布流只需要计算出frame）
    __block NSString *minColumn = @"0";
    //利用block遍历字典,找出高度最小列
    [self.dict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
        //若某列高度较低 则将最低列key做替换
        if ([self.dict[minColumn] floatValue] > [obj floatValue]) {
            minColumn = key;
        }
    }];
    
    CGFloat x = self.sectionEdg.left + [minColumn integerValue] * (self.itemWidth + self.columSpacing);
    CGFloat y = [self.dict[minColumn] floatValue];
    
    CGFloat itemHeight = 0;
    if (self.myBlock != nil) {
        itemHeight = self.myBlock(indexPath,self.itemWidth);
    }else {
        //断言，只有在满足条件的情况下 程序才会往下执行
        NSAssert(0, @"未实现block回调");
    }
    //当获取高度布局后 改变高度最小列的高度
    CGFloat newHeight = y + itemHeight + self.rowSpacing;
    self.dict[minColumn] = [NSNumber numberWithFloat:newHeight];
    //配置frame
    attribute.frame = CGRectMake(x, y, self.itemWidth, itemHeight);
    
    return attribute;
}
/**必须用重载的方法显示视图的大小*/
/**视图显示范围*/
/**返回layout的size。*/
- (CGSize)collectionViewContentSize{
    __block NSString *maxColumn = @"0";
    //利用block遍历字典,找出高度最高列
    [self.dict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
        //若某列高度较低 则将最低列key做替换
        if ([self.dict[maxColumn] floatValue] < [obj floatValue]) {
            maxColumn = key;
        }
    }];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [self.dict[maxColumn] floatValue] - self.rowSpacing + self.sectionEdg.bottom;
    return CGSizeMake(width, height);
}


#pragma mark --UICollectionViewDelegateFlowLayout

//定义每个UICollectionView 的大小
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    return CGSizeMake(96, 100);
//}

//定义每个UICollectionView 的 margin
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    return UIEdgeInsetsMake(5, 5, 5, 5);
//}
@end
